
import * as projects from './project.json';
import * as fs from 'fs';
import * as service from './egg-template/service.json';

const clusters = ["v-dev-one", "v-dev-two"];

interface IConfig {
  node_home: string;
  cluster: string;
  apollo_host: string;
  init_dir: string;
}

const config: IConfig = {
  "node_home": "/root/.nvm/versions/node/v10.15.3",
  "cluster": "",
  "apollo_host": "http://172.21.0.32:8080",
  // "apollo_host": "http://139.199.128.94:8080",
  "init_dir": "/mnt/jenkins_workspace",
  // "init_dir": "/Users/shaoc/svn/node-sh/test"
};

interface IProject {
  name: string;
  port: number[];
  namespace: string[];
}

class InitOneEgg {
  project: IProject;
  config: IConfig;
  bakUrl: string;
  index: number;
  constructor(project: IProject, config: IConfig, index: number) {
    this.project = project;
    this.config = config;
    this.bakUrl = `${config.init_dir}/${config.cluster}_bak`;
    this.index = index;
  }

  public async generate() {
    if (!this.project.port[this.index]) {
      throw `${this.project.name} port 配置不够 ${this.index}`;
    }
    const project_path =  `${this.bakUrl}/${this.project.name}`;
    if (fs.existsSync(project_path)) {
      // fs.rmdirSync(project_path, {recursive: true});
      del(project_path);
      console.log(`已删除 ${project_path}`);
    }
    fs.mkdirSync(project_path, { recursive: true });

    const filename = `${this.bakUrl}/${this.project.name}/config-vars.sh`;
    fs.writeFileSync(filename, this.getConfigVar());
    fs.chmodSync(filename, 0o777);
    // console.log(`${filename} ok!`);

    const data = this.getServiceJson();
    const jsonfile = `${this.bakUrl}/${this.project.name}/service.json`;
    fs.writeFileSync(jsonfile, `${JSON.stringify(data, null, 2)}`);
    // console.log(`${jsonfile} ok!`);

    const shfile = `${this.bakUrl}/${this.project.name}/startup.sh`;
    fs.copyFileSync(`./egg-template/startup.sh`, shfile);
    fs.chmodSync(shfile, 0o777);
    console.log(`OK：${shfile}`);
  }
  
  private getConfigVar() {
    const replaceMap = {
      '{{node_home}}': this.config.node_home,
      '{{project}}': this.project.name,
      '{{cluster}}': this.config.cluster
    };
    var content = fs.readFileSync('./egg-template/config-vars.sh', "utf8");
    return this._doReplace(content.toString(), replaceMap);
  }

  private getServiceJson() {
    const obj = {...service};
    obj.name = this.project.name;
    obj.port = this.project.port[this.index];
    obj.apollo_host = this.config.apollo_host;
    obj.cluster = this.config.cluster;
    obj.namespace = this.project.namespace;
    return obj;
  }


  private _doReplace(content, replaceMap) {
    Object.keys(replaceMap).forEach(e => {
      var reg = "/"+e+"/g";
      content = content.replace(eval(reg), replaceMap[e]);
    })
    return content;
  }
}


async function main() {
  clusters.forEach((cluster, index) => {
    projects.forEach(project => {
      const conig2 = {...config, cluster};
      const obj = new InitOneEgg(project, conig2, index);
      obj.generate();
      console.log('ok')
    })
  })
}
main()

function del(p){
var arr=fs.readdirSync(p);
for(var i in arr){
//读取文件信息，以便于判断是否是一个文件或目录
var stats=fs.statSync(p+'/'+arr[i]);
if(stats.isFile()){
//判断为真，是文件则执行删除文件
fs.unlinkSync(p+'/'+arr[i]);
}else{
//判断为假就是文件夹，就调用自己，递归的入口
del(p+'/'+arr[i]);
}
}
//删除空目录
fs.rmdirSync(p);
}
